package com.rms.recruit_management_system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rms.recruit_management_system.mapper.DepartmentMapper;
import com.rms.recruit_management_system.mapper.PositionsMapper;
import com.rms.recruit_management_system.pojo.Department;
import com.rms.recruit_management_system.pojo.Positions;
import com.rms.recruit_management_system.service.DepartmentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department> implements DepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;
    @Autowired
    private PositionsMapper positionsMapper;
    @Override
    public List<Department> getDepartmentList(Department department) {

        return departmentMapper.selectList(null);
    }

    @Override
    public void addDepartment(Department department) {
        department.setCreateTime(LocalDateTime.now());
        department.setUpdateTime(LocalDateTime.now());
       departmentMapper.insert(department);
    }
    @Override
    public void updateDepartment(Department department) {
        department.setUpdateTime(LocalDateTime.now());
        departmentMapper.updateById(department);
    }

    @Override
    public void deleteDepartment(Integer departmentId) {
        List<Positions> positions = positionsMapper.selectList(new QueryWrapper<Positions>().eq("department_id", departmentId));
        log.info("positions: " + positions);
        List<Integer> departmentIdsToDelete = positions.stream()
                .map(Positions::getDepartmentId)
                .collect(Collectors.toList());
        if (!departmentIdsToDelete.isEmpty()) {
            positionsMapper.delete(new QueryWrapper<Positions>().in("department_id", departmentIdsToDelete));
        }
        departmentMapper.deleteById(departmentId);
    }

    @Override
    public void deleteBatchDepartment(List<Integer> departmentIds) {
        departmentMapper.deleteBatchIds(departmentIds);
    }
}
